package com.beiing.tianshuai.tianshuai.huodong;

import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.adapter.EventsRvAdapter;
import com.beiing.tianshuai.tianshuai.entity.ActiveInfoBean;
import com.beiing.tianshuai.tianshuai.entity.HuoDongItemBean;
import com.beiing.tianshuai.tianshuai.entity.UserInfoBean;
import com.beiing.tianshuai.tianshuai.fragment.BaseLazyLoadFragment;
import com.beiing.tianshuai.tianshuai.huodong.presenter.HuoDongAllPresenter;
import com.beiing.tianshuai.tianshuai.huodong.view.HuoDongAllViewImpl;
import com.beiing.tianshuai.tianshuai.mine.ui.LoginActivity;
import com.beiing.tianshuai.tianshuai.util.DensityUtils;
import com.beiing.tianshuai.tianshuai.widget.CustomDialog;
import com.beiing.tianshuai.tianshuai.widget.CustomEmptyLayout;
import com.beiing.tianshuai.tianshuai.widget.MyRefreshHeader;
import com.beiing.tianshuai.tianshuai.widget.RecycleViewDivider;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 全部活动列表
 *
 * @author magikliu
 * @date 2017/9/10
 */

public class AllEventsFragment extends BaseLazyLoadFragment implements HuoDongAllViewImpl {

    private HuoDongAllPresenter mPresenter;
    private static final int LIST_ROWS = 9;
    private boolean isLoadFinish;
    private int currentRow = 1;
    private EventsRvAdapter mAdapter;
    private List<HuoDongItemBean.DataBean.ActiveBean> activeList;
    private boolean isFirstLoad = true;

    @BindView(R.id.empty_view)
    CustomEmptyLayout celEmptyLayout;
    @BindView(R.id.events_refresh_header)
    MyRefreshHeader mRefreshHeader;
    @BindView(R.id.events_recycler)
    RecyclerView mRecyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mContentView == null) {
            mContentView = inflater.inflate(R.layout.fragment_events_common, container, false);
            mUnbinder = ButterKnife.bind(this, mContentView);
            mContext = getActivity();
            initRecyclerView();
            setPresenter();
        }
        setRefreshLayout();
        return mContentView;
    }

    private void setPresenter() {
        mPresenter = new HuoDongAllPresenter(this);
        mPresenter.getAllHuoDong(currentRow, LIST_ROWS, 0);
    }

    private void setRefreshLayout() {
        mRefreshLayout.setRefreshHeader(new MyRefreshHeader(mContext));
        mRefreshLayout.setRefreshFooter(new ClassicsFooter(mContext));

        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                currentRow = 1;
                mPresenter.getAllHuoDong(currentRow, LIST_ROWS, 1);
                mRefreshHeader.onFinish(mRefreshLayout, true);
            }
        });
        mRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                if (!isLoadFinish) {
                    mPresenter.getAllHuoDong(currentRow, LIST_ROWS, 0);
                }
            }
        });
    }

    private void initRecyclerView() {
        activeList = new ArrayList<>();
        mAdapter = new EventsRvAdapter(activeList, getActivity());
        LinearLayoutManager manager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        mRecyclerView.setNestedScrollingEnabled(false);
        mRecyclerView.setLayoutManager(manager);
        mRecyclerView.addItemDecoration(
                new RecycleViewDivider(
                        mContext, LinearLayoutManager.HORIZONTAL, DensityUtils.dp2px(mContext, 0.5f),
                        ContextCompat.getColor(mContext, R.color.divider_gray_light_efefef))
        );
        mRecyclerView.setAdapter(mAdapter);

        mAdapter.setOnItemViewClickListener(new EventsRvAdapter.OnItemViewClickListener() {
            @Override
            public void onItemViewClick(View v, int position) {
                switch (v.getId()) {
                    case R.id.huodong_price:
                        mAdapter.setOnItemClickListener(null);
                        if (TextUtils.isEmpty(UserInfoBean.getUid(mContext))) {
                            startActivity(new Intent(mContext, LoginActivity.class));
                        } else if ("1".equals(activeList.get(position).getIs_three())) {
                            showBookingDialog(position);
                        } else if (Integer.parseInt(activeList.get(position).getCount()) > 0) {
                            ActiveInfoBean orderBean = new ActiveInfoBean();
                            orderBean.setAid(activeList.get(position).getId());
                            orderBean.setTitle(activeList.get(position).getStrech());
                            orderBean.setCover(activeList.get(position).getCover());
                            orderBean.setPrice(activeList.get(position).getMuch());
                            orderBean.setRestCount(activeList.get(position).getCount());

                            // 跳转并传递所需的活动信息
                            Intent orderIntent = new Intent();
                            orderIntent.setClass(mContext, ActivitiesApplyForActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("activeInfo", orderBean);
                            orderIntent.putExtras(bundle);
                            startActivity(orderIntent);
                        } else {
                            showShortText("暂时没有多余的票了");
                        }
                        break;
                    default:
                        mAdapter.setOnItemClickListener(new EventsRvAdapter.OnItemClickListener() {
                            @Override
                            public void onItemClick(View v, int position) {
                                //带值跳转
                                Intent intent = new Intent(getActivity(), ActivitiesDetailActivity.class);
                                Bundle bundle = new Bundle();
                                bundle.putSerializable("active", activeList.get(position));
                                intent.putExtras(bundle);
                                intent.putExtra("active_id", activeList.get(position).getId());
                                startActivity(intent);
                            }
                        });
                }
            }
        });
    }

    private void showBookingDialog(final int position) {
        CustomDialog customDialog = new CustomDialog(mContext, R.style.dialog,
                "此票为第三方平台出售，点击确定跳转到购票地址",
                new CustomDialog.OnCloseListener() {
                    @Override
                    public void onClick(Dialog dialog, boolean confirm) {
                        Uri bookingUri = Uri.parse(activeList.get(position).getThree_url());
                        Intent intent = new Intent(Intent.ACTION_VIEW, bookingUri);
                        startActivity(intent);
                    }
                }).setTitle("提示");
        customDialog.setCanceledOnTouchOutside(true);
        customDialog.show();
    }

    @Override
    public void showAllHuoDong(HuoDongItemBean bean) {
        List<HuoDongItemBean.DataBean.ActiveBean> activeBeen = bean.getData().getActive();
        int size = activeBeen.size();
        if (size == 0) {
            isLoadFinish = true;
            showShortText("已加载全部内容");
        } else if (size < LIST_ROWS) {
            isLoadFinish = false;
            currentRow++;
            activeList.addAll(activeBeen);
            mAdapter.notifyDataSetChanged();
        } else {
            isLoadFinish = false;
            currentRow++;
            activeList.addAll(activeBeen);
            mAdapter.notifyDataSetChanged();
        }
        if (mRefreshLayout != null && (mRefreshLayout.isRefreshing() || mRefreshLayout.isLoading())) {
            mRefreshLayout.finishRefresh();
            mRefreshLayout.finishLoadmore();
        }
        isLoadedOnce = true;
    }

    /**
     * 下拉刷新获取数据
     *
     * @param bean 数据
     */
    @Override
    public void refreshHuoDong(HuoDongItemBean bean) {
        List<HuoDongItemBean.DataBean.ActiveBean> activeBeen = bean.getData().getActive();
        int size = activeBeen.size();
        if (size == 0) {
            isLoadFinish = true;
            mRefreshLayout.setLoadmoreFinished(true);
        } else if (size < LIST_ROWS) {
            isLoadFinish = false;
            currentRow++;
            activeList.clear();
            activeList.addAll(activeBeen);
            mAdapter.notifyDataSetChanged();
            mRefreshLayout.setLoadmoreFinished(false);
        } else {
            isLoadFinish = false;
            currentRow++;
            activeList.clear();
            activeList.addAll(activeBeen);
            mAdapter.notifyDataSetChanged();
            mRefreshLayout.setLoadmoreFinished(false);
        }
        if (mRefreshLayout != null && (mRefreshLayout.isRefreshing() || mRefreshLayout.isLoading())) {
            mRefreshLayout.finishRefresh();
            mRefreshLayout.finishLoadmore();
        }
    }

    @Override
    public void showProgress() {
        if (celEmptyLayout != null && isFirstLoad) {
            celEmptyLayout.setInProgress();
            isFirstLoad = false;
        }
    }

    @Override
    public void hideProgress() {
        if (celEmptyLayout != null) {
            celEmptyLayout.setChildrenVisible();
        }
    }

    @Override
    public void showError(int errorType) {
        switch (errorType) {
            case 0:
                showShortText("数据获取错误，请检查您的网络");
                if (mRefreshLayout != null && (mRefreshLayout.isRefreshing() || mRefreshLayout.isLoading())) {
                    mRefreshLayout.finishRefresh(false);
                    mRefreshLayout.finishLoadmore(false);
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void lazyLoad() {
        if (!isPrepared || isVisible || isLoadedOnce) {
            return;
        }
        mPresenter.getAllHuoDong(currentRow, LIST_ROWS, 0);
    }
}
